<?php

namespace App\Backend\Service;

use App\Models\Categorymapping;
use App\Exceptions\InvalidRequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Backend\Service\BaseService;
use Illuminate\Support\Facades\Cache;
class CategorymappingService extends BaseService
{

    private $model;

    public function __construct(Categorymapping $model)
    {
        parent ::__construct();
        $this->model = $model;
    }

    #更新缓存分类名称
    public function updateMappingCache($request,$data=[])
    {
        $list=$this->model->select(['original_name','standard_name'])->get()->toArray();
        foreach ($list as $key => $value) {
            $this->updateCategoryMappingCache($value['original_name'],$value['standard_name']);
        }
    }

    # 列表
    public function getList($request,$data=[])
    {
        $page = intval($request->json('page')) ?: $this->cpage;
        $limit = intval($request->json('limit')) ?: $this->climit;
        $offset = ($page - 1) * $limit;

        // 构建查询条件
        $query = $this->model->select(['id', 'original_name', 'standard_name', 'status'])
            ->where('status', '1');

        // 添加关键词搜索条件
        if (isset($data['keyword']) && !empty(trim($data['keyword']))) {
            $keyword = trim($data['keyword']);
            $query->where(function($q) use ($keyword) {
                $q->where('original_name', 'like', "%{$keyword}%")
                  ->orWhere('standard_name', 'like', "%{$keyword}%");
            });
        }

        // 获取总数（在分页前）
        $count = $query->count();

        // 执行分页查询
        $list = $query->orderBy('update_time', 'desc')
            ->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get()
            ->toArray();

        // 计算总页数
        $total_page = ceil($count / $limit);

        $result = [
            'page' => $page,
            'limit' => $limit,
            'count' => $count,
            'total_page' => $total_page,
            'data' => $list,  // 这里应该是 $list 而不是 $data
        ];

        return $result;

    }
      /**
     * 添加
     */
    public function add($request,$data)
    {
        $data['original_name']=cleanTextThoroughly($data['original_name']);
        $data['standard_name']=cleanTextThoroughly($data['standard_name']);
        $where=[
            'original_name'=>$data['original_name'],
            'standard_name'=>$data['standard_name'],
        ];
        $original_name=$data['original_name'];
        $data['status']='1';
        $first=$this->model->where($where)->first();
        $result = '未知';
        if($first){
            $data['create_time'] =date("Y-m-d H:i:s");
            $this->model->where($where)->update($data);
            $result =$first['standard_name'];
        }else{
            $data['create_time'] =date("Y-m-d H:i:s");
            $data['update_time'] =date("Y-m-d H:i:s");

            $res=$post_id=$this->model->insertGetId($data);
            $result =$data['standard_name'];
        }

        $this->updateCategoryMappingCache($original_name, $result);
    }
    #详情
    public function detail($request,$id)
    {
        $res = $this->model->where('id',$id)->first();
        return $res;
    }
    /**
     * 更新分类映射缓存
     */
    public function updateCategoryMappingCache($original_name, $result)
    {
        $cacheKey = 'category_mapping:' . md5($original_name);
        
        // 强制更新缓存
        cache()->forget($cacheKey); // 先清除
        cache()->put($cacheKey, $result, 3600); // 再写入
        
        return true;
    }
    /**
     * 编辑
     */
    public function edit($request,$data,$id)
    {
        $data['original_name']=cleanTextThoroughly($data['original_name']);
        $data['standard_name']=cleanTextThoroughly($data['standard_name']);
        $res = $this->model->where('id',$id)->first();
        if(!$res) {
            $this->error('内容不存在');
        }
        
        $data['update_time'] = date("Y-m-d H:i:s");

        $res =  $this->model->where('id',$id)->update($data);


        if(!$res){
            if($data['original_name']){
                $this->updateCategoryMappingCache($data['original_name'], $data['standard_name']);
            }

            $this->error('修改失败');
        }else{
            $this->success();
        }
    }   

     /**
     * 删除
     */
    public function del($ids)
    {
        $res =  $this->model->whereIn('id',$ids)->delete();
        if(!$res){
            $this->error('删除失败');
        }else{
            $this->success();
        }
    }   
    


}
